package com.cuixichang.minimalism.core.security.access;

import com.cuixichang.minimalism.core.security.core.specials.SecurityQuantity;
import com.cuixichang.minimalism.core.security.enums.RouterRelationTypePrefixEnum;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Iterator;

@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {

    /** Logger available to subclasses. */
    @Override
    public void decide(Authentication authentication, Object object,
                       Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {
        // 当接口未被配置资源时直接放行
        if (!CollectionUtils.isEmpty(configAttributes)) {
            Iterator<ConfigAttribute> iterator = configAttributes.iterator();
            while (iterator.hasNext()) {
                ConfigAttribute configAttribute = iterator.next();
                //将访问所需资源或用户拥有资源进行比对
                String needAuthority = configAttribute.getAttribute();
                if(RouterRelationTypePrefixEnum.Role.getPrefix().concat(SecurityQuantity.defaultRole)
                        .equals(needAuthority)) return;
                for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                    if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                        return;
                    }
                }
            }

            if(authentication instanceof AnonymousAuthenticationToken){
                throw new BadCredentialsException("用户身份信息验证不通过，无法执行请求");
            }
            throw new AccessDeniedException("抱歉，您没有访问权限");
        }
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
